﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PersonaLibrary.Data;
using PersonaLibrary.Validation;

namespace PersonaLibrary.ViewModel.EmployeeNoteLinkViewModel
{
	internal sealed class NoteToEmployees : LinqEditableItem<EmployeeNoteLink>
	{
		private readonly ValidationItem _notValid = new ValidationItem();
		private IEnumerable<Employee> _employees;

		public NoteToEmployees(IEnumerable<Employee> arg)
		{
			_employees = arg;
			Init();
		}

		private void Init()
		{
			
		}

		public ValidationItem NotValid
		{
			get
			{
				return _notValid;
			}
		}

		public override bool CanCommit()
		{
			return true;
		}

		public override void Commit()
		{
			Note note;

			if (!_notValid.IsValid)
			{
				note = new Note{ Name = _notValid.ValidationValue.Key };
				Context.Notes.InsertOnSubmit(note);
				Context.SubmitChanges();
			}
			else
				note = Context.Notes.Single(x => x.Name == _notValid.ValidationValue.Key);

			IEnumerable<EmployeeNoteLink> links = Context.EmployeeNoteLinks.Where(x => x.NoteId == note.Id);
			foreach (Employee employee in _employees)
			{
				if (links.Any(x => x.EmployeeId == employee.Id))
					continue;

				EmployeeNoteLink newLink = new EmployeeNoteLink { EmployeeId = employee.Id, NoteId = note.Id };

				Context.EmployeeNoteLinks.InsertOnSubmit(newLink);
			}

			Context.SubmitChanges();

			base.Commit();
		}
	}
}
